package com.swak.boot.config.consistency.tcc;

import static com.swak.boot.Application.APP_LOGGER;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.swak.Constants;
import com.swak.consistency.tcc.config.TccConfig;
import com.swak.consistency.tcc.context.TccContext;
import com.swak.consistency.tcc.handle.TccConsistencyHandler;
import com.swak.consistency.tcc.resolve.DefTccContextResolver;
import com.swak.consistency.tcc.schedule.TccScheduler;

@Configuration
@ConditionalOnClass({ TccContext.class })
@ConditionalOnProperty(prefix = Constants.APPLICATION_PREFIX, name = "enableTcc", matchIfMissing = false)
@EnableConfigurationProperties(TccProperties.class)
@Import({ MysqlTransLogStorageAutoConfiguration.class, DubboResolverAutoConfiguration.class,
		DubboReferenceAutoConfiguration.class })
public class TccConsistencyAutoConfiguration {

	public TccConsistencyAutoConfiguration() {
		APP_LOGGER.debug("Loading Tcc");
	}

	/**
	 * Tcc 配置
	 * 
	 * @return
	 */
	@Bean
	public TccConfig tccConfig(TccProperties properties) {
		return new TccConfig().setModule(properties.getModule()).setRetryTimes(properties.getRetryTimes())
				.setTimeout(properties.getTimeout());
	}

	/**
	 * Tcc 重试任务
	 * 
	 * @return
	 */
	@Bean
	public TccScheduler tccScheduler(TccConfig config) {
		return new TccScheduler(config);
	}

	/**
	 * Tcc 处理器
	 * 
	 * @return
	 */
	@Bean
	public TccConsistencyHandler TccConsistencyHandler() {
		return new TccConsistencyHandler();
	}

	/**
	 * 托底的上下文处理器
	 * 
	 * @return
	 */
	@Bean
	public DefTccContextResolver defTccContextResolver() {
		return new DefTccContextResolver();
	}
}
